/**
 * 包含多选框的下拉列表，含全选和全不选操作
 * */
import { useEffect, useState, useCallback, useRef } from 'react';
import { Checkbox, Button } from 'antd';
import 'less/components/checkbox-select/index.less';

function CheckboxSelect(props: { optionsList: any; changeCallback: any }) {
  const { optionsList, changeCallback } = props;

  const cancelBtn: any = useRef();
  const [showText, setShowText] = useState('全部');
  const [isActive, setIsActive] = useState(false);
  const [checkAll, setCheckAll] = useState(true);
  const [indeterminate, setIndeterminate] = useState(false);
  const [checkboxValList, setCheckboxValList] = useState([]);
  const [checkboxOldValList, setCheckboxOldValList] = useState([]);

  // 多选框列表被触发的时候
  const checkboxChange = (list: any) => {
    setCheckboxValList(list);
    setIndeterminate(!!list.length && list.length < optionsList.length);
  };
  // 确定操作
  const confirm = () => {
    setCheckboxOldValList(checkboxValList);
    setIsActive(false);

    // 返回最终数据
    changeCallback(checkboxValList);

    // 把选择的文本显示在框框内
    if (checkboxValList.length === optionsList.length) {
      setShowText('全部');
      return;
    }
    const textArr: any = [];
    optionsList.forEach((item1: any) => {
      checkboxValList.forEach(item2 => {
        if (item1.value === item2) {
          textArr.push(item1.label);
        }
      });
    });
    setShowText(textArr.join('，'));
  };
  // 取消操作
  const cancel = () => {
    setCheckboxValList(checkboxOldValList);
    setIsActive(false);
  };
  // 点击操作
  const toggleClick = (ev: any) => {
    // 阻止事件冒泡
    ev.nativeEvent.stopImmediatePropagation();
    const status = !isActive;
    setIsActive(status);
  };

  // 全选/全不选 操作
  const onCheckAllChange = () => {
    const status = !checkAll;
    setCheckAll(status);

    // 判断是全选还是全不选
    const listArr: any = [];
    if (status) {
      optionsList.forEach((item: any) => {
        listArr.push(item.value);
      });
    }
    setCheckboxValList(listArr);
    setIndeterminate(false);
  };

  // 触发内容区域
  const documentEvent = () => {
    (cancelBtn as any).current.click();
  };

  // 监听全选/全不选状态
  useEffect(() => {
    setCheckAll(optionsList.length === checkboxValList.length);
    setIndeterminate(!!checkboxValList.length && checkboxValList.length < optionsList.length);
  }, [checkboxValList]);

  // 组件卸载
  const unComponent = () => {
    // console.log('组件卸载');
    document.removeEventListener('click', documentEvent);
  };

  // 初始操作
  const init = useCallback(() => {
    // 设置checkbox默认全选
    const listArr: any = [];
    optionsList.forEach((item: any) => {
      listArr.push(item.value);
    });
    setCheckboxValList(listArr);
    setCheckboxOldValList(listArr);
    // 空白文档处被点击
    document.addEventListener('click', documentEvent);
  }, []);

  useEffect(() => {
    init();
    return unComponent;
  }, []);

  return (
    <>
      <div className={`checkbox-select ${isActive ? 'checkbox-select-active' : ''}`}>
        <div className='cs__input-wrap' onClick={toggleClick}>
          <div className='cs__input-text'>{showText}</div>
          <span className='cs__input-icon'></span>
        </div>
        <div
          className='cs__tool'
          onClick={ev => {
            ev.nativeEvent.stopImmediatePropagation();
          }}
        >
          <Checkbox.Group onChange={checkboxChange} value={checkboxValList}>
            <ul className='cs__checkbox-list'>
              {optionsList.length ? (
                optionsList.map((item: any) => {
                  return (
                    <li key={item.value}>
                      <Checkbox value={item.value}>{item.label}</Checkbox>
                    </li>
                  );
                })
              ) : (
                <li className='empty'>暂无数据</li>
              )}
            </ul>
          </Checkbox.Group>

          <div className='cs__button' style={{ display: optionsList.length ? '' : 'none' }}>
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选/全不选
            </Checkbox>
            <Button type='primary' size='small' onClick={confirm}>
              确定
            </Button>
            <Button size='small' onClick={cancel} ref={cancelBtn}>
              取消
            </Button>
          </div>
        </div>
      </div>
    </>
  );
}

export default CheckboxSelect;
